package com.gpframework.module.wages.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.exception.BaseException;
import com.gpframework.common.exception.CustomException;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.module.wages.domain.*;
import com.gpframework.module.wages.domain.req.GzWarehouseEvaluationUpdate;
import com.gpframework.module.wages.domain.vo.GzWarehouseEvaluationVo;
import com.gpframework.module.wages.mapper.GzWarehouseEvaluationMapper;
import com.gpframework.module.wages.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * @ClassName GzWarehouseEvaluation
 * @Author gpframework
 * @Date 2024-01-19
 * @Version 1.0.0
 * @Description 仓库评定Service业务层处理
 */
@Service
public class GzWarehouseEvaluationServiceImpl extends ServiceImpl<GzWarehouseEvaluationMapper, GzWarehouseEvaluation> implements IGzWarehouseEvaluationService {


    @Autowired
    private  IGzMonthlyLeaveService iGzMonthlyLeaveService;
    @Autowired
    private  IGzAttendanceManagementService iGzAttendanceManagementService;
    @Autowired
    private  IGzWarehousePersonnelService iGzWarehousePersonnelService;
    @Autowired
    private  IGzTotalSalesOfTheCompanyService iGzTotalSalesOfTheCompanyService;

    @Autowired
    private IGzPersonnelFoundationService iGzPersonnelFoundationService;
    @Autowired
    private IGzWarehouseEvaluationService iGzWarehouseEvaluationService;


    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2024-01-19
     * @Param [lqw]
     * @Return List<GzWarehouseEvaluationVo>
     */
    @Override
    public List<GzWarehouseEvaluationVo> listVo(QueryWrapper<GzWarehouseEvaluation> lqw) {
        return this.baseMapper.listVo(lqw);
    }

    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2024-01-19
     * @Param [id]
     * @Return GzWarehouseEvaluationVo
     */
    @Override
    public GzWarehouseEvaluationVo getVoById(Long id) {
        return this.baseMapper.getVo(id);
    }

    @Override
    public void deleteByMonth(Date yearMonth) {
        this.baseMapper.deleteByMonth(yearMonth);
    }

    @Override
    public boolean editBatch(List<GzWarehouseEvaluationUpdate> list) {
        ArrayList<GzWarehouseEvaluation> updateList = new ArrayList<>();
        for (GzWarehouseEvaluationUpdate gzWarehouseEvaluationUpdate : list) {
            GzWarehouseEvaluation gzWarehouseEvaluation = Convert.convert(new TypeReference<GzWarehouseEvaluation>() {}, gzWarehouseEvaluationUpdate);

            //考勤管理
            GzAttendanceManagement attendanceManagement = iGzAttendanceManagementService.getOne(new QueryWrapper<GzAttendanceManagement>().eq("user_id", gzWarehouseEvaluationUpdate.getUserId()).like("month", DateUtils.parseDateToStr("yyyy-MM", gzWarehouseEvaluationUpdate.getMonth())));
            if(attendanceManagement==null){
                throw new BaseException("请填入考勤信息");
            }
            //获取对应的月度假数
            GzMonthlyLeave gearopening  =iGzMonthlyLeaveService.getOne(new QueryWrapper<GzMonthlyLeave>().eq("user_id", gzWarehouseEvaluationUpdate.getUserId()).like("month", DateUtils.parseDateToStr("yyyy-MM", gzWarehouseEvaluationUpdate.getMonth())));

            //当月按天数绩效
            gzWarehouseEvaluation.setMonthlyPerformanceByDays((gzWarehouseEvaluation.getPerformanceCoefficient()*attendanceManagement.getAttendanceDays())/gearopening.getRequireDateNdancedays());
            GzTotalSalesOfTheCompany gzTotalSalesOfTheCompany = iGzTotalSalesOfTheCompanyService.getOne(new QueryWrapper<GzTotalSalesOfTheCompany>().eq("month", gzWarehouseEvaluationUpdate.getMonth()));

            if (gzWarehouseEvaluation.getEvaluationCriteriaBonus().equals("0")){
                gzWarehouseEvaluation.setMonthlyEvaluationBonus(BigDecimal.ZERO.multiply(gzWarehouseEvaluation.getManagerEvaluation()));
            }else {
                String[] split = gzWarehouseEvaluation.getEvaluationCriteriaBonus().split("-");
                BigDecimal monthlyEvaluationBonus = new BigDecimal(split[1]);
                //计算月度评定奖金 =经理评定 *标准金额
                if (gzWarehouseEvaluation.getManagerEvaluation().compareTo(BigDecimal.ONE)>0){
                    throw new BaseException("经理评定不能大于1");
                }
                //月度评定奖金=评定标准奖金*经理评定
                gzWarehouseEvaluation.setMonthlyEvaluationBonus(monthlyEvaluationBonus.multiply(gzWarehouseEvaluation.getManagerEvaluation()));
            }


            //if (gzWarehouseEvaluation.getMonthlyEvaluationBonus().compareTo(evaluationCriteriaBonus0) < 0 ||
            //        gzWarehouseEvaluation.getMonthlyEvaluationBonus().compareTo(evaluationCriteriaBonus1) > 0) {
            //  throw new BaseException("请根据评定标准奖金，输入月度评定奖金");
            //}
            //gzWarehouseEvaluation.setMonthlyEvaluationBonus(gzWarehouseEvaluation.getMonthlyEvaluationBonus());


            if (gzTotalSalesOfTheCompany ==null){
                throw new BaseException("请去公司总销售，求出月平均绩效金额");
            }
           // 月度绩效奖金
            gzWarehouseEvaluation.setMonthlyPerformanceBonus(gzTotalSalesOfTheCompany.getMonthlyAveragePerformanceAmount().multiply(BigDecimal.valueOf(gzWarehouseEvaluation.getMonthlyPerformanceByDays())));


            updateList.add(gzWarehouseEvaluation);
        }

        return this.updateBatchById(updateList);
    }

    @Override
    public String importListNote(List<GzWarehouseEvaluationVo> excelList, boolean updateSupport) {
        if (StringUtils.isNull(excelList) || excelList.size() == 0) {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (GzWarehouseEvaluationVo gzWarehouseEvaluationVo : excelList) {
            try {
                //查询数据
                GzWarehouseEvaluation warehouseEvaluation = iGzWarehouseEvaluationService.getOne(new QueryWrapper<GzWarehouseEvaluation>()
                        .eq("name", gzWarehouseEvaluationVo.getName())
                        .eq("department_name", gzWarehouseEvaluationVo.getDepartmentName())
                        .eq("month", gzWarehouseEvaluationVo.getMonth())
                        .eq("del_status", YesNoEnum.NO.getKey()));
                if (StringUtils.isNull(warehouseEvaluation)){
                    //新增仓库评定
                    GzWarehouseEvaluation gzWarehouseEvaluation = Convert.convert(new TypeReference<GzWarehouseEvaluation>() {
                    }, gzWarehouseEvaluationVo);

                    //复制userId
                    GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                            .eq("name", gzWarehouseEvaluationVo.getName())
                            .eq("department_name", gzWarehouseEvaluationVo.getDepartmentName())
                            .eq("del_status", YesNoEnum.NO.getKey()));

                    gzWarehouseEvaluation.setUserId(gzPersonnelFoundation.getId());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、姓名 " + gzWarehouseEvaluation.getName() + " 导入成功");
                    iGzWarehouseEvaluationService.save(gzWarehouseEvaluation);
                } else if (updateSupport) {
                    //更新仓库评定
                    GzWarehouseEvaluation gzWarehouseEvaluation = Convert.convert(new TypeReference<GzWarehouseEvaluation>() {
                    }, gzWarehouseEvaluationVo);

                    GzWarehouseEvaluation evaluation = iGzWarehouseEvaluationService.getOne(new QueryWrapper<GzWarehouseEvaluation>()
                            .eq("name", gzWarehouseEvaluationVo.getName())
                            .eq("department_name", gzWarehouseEvaluationVo.getDepartmentName())
                            .eq("month", gzWarehouseEvaluationVo.getMonth())
                            .eq("del_status", YesNoEnum.NO.getKey()));
                    if (evaluation!=null){
                        //获取ID
                        gzWarehouseEvaluation.setId(evaluation.getId());
                    }

                    //复制userId
                    GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                            .eq("name", gzWarehouseEvaluationVo.getName())
                            .eq("department_name", gzWarehouseEvaluationVo.getDepartmentName())
                            .eq("del_status", YesNoEnum.NO.getKey()));
                    gzWarehouseEvaluation.setUserId(gzPersonnelFoundation.getId());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、姓名 " + gzWarehouseEvaluation.getName() + " 更新成功");
                    iGzWarehouseEvaluationService.updateById(gzWarehouseEvaluation);
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名 " + gzWarehouseEvaluationVo.getName() + " 已存在");
                }

            }catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、姓名 " + gzWarehouseEvaluationVo.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<GzWarehouseEvaluationVo> listVoed(QueryWrapper<GzWarehouseEvaluation> lqw) {
        return this.baseMapper.listVoed(lqw);
    }
}
